const WebSocket = require('ws');

const server = new WebSocket.Server({ port: 8181 });

server.on('connection', (ws) => {
    console.log('有客户端连接');

    ws.on('message', (message) => {
        let msg = JSON.parse(message);
        server.clients.forEach(function each(client) {
            if (client.readyState === WebSocket.OPEN) {
                client.send(JSON.stringify(msg));
            }
        });
    });

    ws.on('error', function (error) {
        console.error('WebSocket 发生错误:', error);
    });
    ws.send(JSON.stringify({userid: '系统ID',message:'你好，有什么是我可以帮你的吗？'}));
});

server.on('listening', function () {
    console.log('WebSocket 服务器正在监听 8181 端口');
});

server.on('error', function (error) {
    console.error('WebSocket 服务器发生错误:', error);
});

module.exports = server;